package IOBaseTest;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * Created by yexuan on 2018/3/17.
 * 管道输入流可直接连接欸管道输出流，无需中转
 * 因为read方法是阻塞式方法  所以管道流建议使用双线程 避免出现read为空时发生阻塞
 */

class Read implements Runnable{
    private PipedInputStream pipedInputStream;

    public Read(PipedInputStream pipedInputStream) {
        this.pipedInputStream = pipedInputStream;
    }
    @Override
    public void run() {
        try {
            byte[] bytes = new byte[1024];
            int num = pipedInputStream.read(bytes);
            System.out.println(new String(bytes,0,num));
            pipedInputStream.close();
        }catch (Exception e){
            throw new RuntimeException("Read Exception");
        }
    }
}
class Write implements Runnable{
    private PipedOutputStream pipedOutputStream;

    public Write(PipedOutputStream pipedOutputStream) {
        this.pipedOutputStream = pipedOutputStream;
    }
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            pipedOutputStream.write("hello world!".getBytes());
            pipedOutputStream.close();
        }catch (Exception e){
            throw new RuntimeException("Write Exception");
        }
    }
}

public class PipedStreamDemo {
    public static void main(String[] args) throws IOException {
        PipedInputStream pipedInputStream = new PipedInputStream();
        PipedOutputStream pipedOutputStream = new PipedOutputStream();
        pipedInputStream.connect(pipedOutputStream);
        Read read = new Read(pipedInputStream);
        Write write = new Write(pipedOutputStream);
        Thread t1 = new Thread(read);
        Thread t2 = new Thread(write);

        t1.start();
        t2.start();
    }
}
